<?php
	/*
	 * This file is part of phpitter.
 	 * 
	 * phpitter is free software: you can redistribute it and/or modify
	 * it under the terms of the GNU General Public License as published by
	 * the Free Software Foundation, either version 3 of the License, or
	 * (at your option) any later version.
 	 * 
	 * phpitter is distributed in the hope that it will be useful,
	 * but WITHOUT ANY WARRANTY; without even the implied warranty of
	 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	 * GNU General Public License for more details.
 	 * 
	 * You should have received a copy of the GNU General Public License
	 * along with phpitter.  If not, see <http://www.gnu.org/licenses/>.
	 *
	 * Copyright 2008 Ryan Hadley
	 */

	function createBookmarks($tweetText)
	{
		$bookmarks = loadBookmarks();

		preg_match('|[\w]+://[a-zA-Z][\S]*|', $tweetText, $links);
		if ( count($links) > 0 )
		{
			foreach ( $links as $link )
			{
				bookmark($link, $tweetText, $bookmarks);
			}
		}

		saveBookmarks(&$bookmarks);
		writeBookmarksXML($bookmarks);

		return($tweetText);
	}

	function loadBookmarks()
	{
		global $phpTwitter;

		$bookmarks = array();

		if ( is_readable($phpTwitter->username . '.bookmarks.phpitter'))
			$bookmarks = unserialize(file_get_contents($phpTwitter->username . '.bookmarks.phpitter'));

		return $bookmarks;
	}

	function saveBookmarks($bookmarks)
	{
		global $phpTwitter;

		file_put_contents($phpTwitter->username . '.bookmarks.phpitter', serialize($bookmarks));
	}

	function bookmark($link, $description, &$bookmarks)
	{
		if ( ! array_key_exists($link, $bookmarks) )
		{
			$bookmarks[$link] = $description;
		}
	}

	function writeBookmarksXML($bookmarks)
	{
		global $phpTwitter;

		$bookmarks = array_reverse($bookmarks);

		$xml = '<?xml version="1.0"?>';
		$xml .= '<rss version="2.0">';
		$xml .= '<channel>';
		$xml .= '<title>Collected Twitter Links</title>';
		$xml .= '<description>Links collected out of your public timeline</description>';
		$count = 0;
		foreach ( $bookmarks as $link => $description )
		{
			$xml .= '<item>';
			$xml .= '<title>' . htmlentities(substr($description, 0, 60)) . '</title>';
			$xml .= '<link>' . $link . '</link>';
			$xml .= '<description>' . htmlentities($description) . '</description>';
			$xml .= '</item>';

			$count++;
			if ( $count == 50 )
				break;
		}
		$xml .= '</channel>';
		$xml .= '</rss>';

		file_put_contents($phpTwitter->username . '.bookmarks.phpitter.xml', $xml);

		$html = '<html><head>';
		$html .= '<link rel="alternate" type="application/rss+xml" title="Collected Twitter Links" href="' . $phpTwitter->username . '.bookmarks.phpitter.xml" />';
		$html .= '</head><body>Use this live bookmark</body></html>';

		file_put_contents($phpTwitter->username . '.bookmarks.phpitter.html', $html);
	}

	$pluggable->registerDisplayTweetCallback('createBookmarks');
?>
